import { Button, Space, TypographyText } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { cinemaApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, downloadWithoutName, formatDate } from '@/utils'
import { activityTypeOptions } from '@/views/order/constants'

export default defineComponent({
  name: 'DyTimeLimitManage',
  setup() {
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '活动名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入关键字搜索',
                  allowClear: true
                }
              }
            },
            {
              title: '活动类型',
              field: 'activityType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: activityTypeOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            title: '活动名称',
            field: 'activityName',
            minWidth: 200
          },
          {
            title: '活动类型',
            field: 'activityType',
            minWidth: 150,
            formatter: ({ cellValue }) => {
              switch (cellValue) {
                case 1:
                  return '营销活动会员日'
                case 2:
                  return '金豆折扣'
                case 3:
                  return '现金折扣'
                case 4:
                  return '金豆抵现折扣'
                default:
                  return ''
              }
            }
          },
          {
            title: '活动期限',
            minWidth: 310,
            slots: {
              default: 'timeRangeRow'
            }
          },
          {
            title: '活动区域',
            minWidth: 120,
            slots: {
              default: 'square'
            }
          },
          {
            title: '活动影院',
            minWidth: 250,
            slots: {
              default: 'cinema'
            }
          },
          {
            title: '适用人群',
            minWidth: 200,
            slots: {
              default: 'people'
            }
          },
          {
            title: '状态',
            field: 'status',
            fixed: 'right',
            width: 100,
            slots: {
              default: 'status'
            }
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 250
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await cinemaApi.getActivityList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()

    function handleCreate() {
      router.push({
        name: 'DyCreateLimit'
      })
    }

    function handleEdit(row) {
      router.push({
        name: 'DyCreateLimit',
        query: {
          id: row.id
        }
      })
    }

    function handleDisable(data) {
      showConfirm({
        content: data.status == 1 ? '确认禁用该活动？' : '确认启用该活动？',
        onOk: async () => {
          try {
            await cinemaApi.activityChange(data.id)
            await tableRef.value.table.commitProxy('query')
          } catch (error) {}
        }
      })
    }

    async function handleExport(id: number) {
      try {
        const res = await cinemaApi.activityExport(id)
        downloadWithoutName(res, '订单详情.csv')
      } finally {
      }
    }

    onMounted(() => {
      bus.on('refreshTimeLimitList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      tableConfig,
      handleCreate,
      handleEdit,
      handleDisable,
      handleExport
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            timeRangeRow: ({ row }) => (
              <Space>
                <span>
                  {row.activityStartTime
                    ? `${formatDate(row.activityStartTime)}至${formatDate(
                        row.activityEndTime
                      )}`
                    : ''}
                </span>
              </Space>
            ),
            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">禁用</TypographyText>
                  ) : (
                    <TypographyText type="success">启用</TypographyText>
                  )}
                </Space>
              )
            },
            square: ({ row }) => (
              <Space>
                {row.province ? (
                  <span>{`${row.province}${row.city ? row.city : ''}`}</span>
                ) : (
                  '全国'
                )}
              </Space>
            ),
            cinema: ({ row }) => (
              <Space>
                {row.cinemaType == 0 ? (
                  '全部影院'
                ) : (
                  <div>
                    {row.cinemas.map(val => {
                      return <div>{`${val}；`}</div>
                    })}
                  </div>
                )}
              </Space>
            ),
            people: ({ row }) => (
              <Space>
                {row.peopleType == 0 ? (
                  '无限制'
                ) : (
                  <div>
                    {row.people.map(val => {
                      return <div>{`${val.name} ${val.phone}；`}</div>
                    })}
                  </div>
                )}
              </Space>
            ),
            paySet: ({ row }) => (
              <Space>
                <span>
                  {row.payType == 0 ? '纯金豆支付' : `${row.payGoldBean}折`}
                </span>
              </Space>
            ),
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDisable(row)}
                >
                  {row.status == 1 ? '禁用' : '启用'}
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleExport(row.id)}
                >
                  导出订单详情
                </Button>
              </Space>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button type="primary" onClick={this.handleCreate}>
                    新增限时活动
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
